package com.englisheveryday.net;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.englisheveryday.constants.Constants;
import com.englisheveryday.net.Downloader.OnCompleteListener;
import com.englisheveryday.net.Downloader.OnFileNotExistListener;

/**
 * <pre>
 * </pre>
 * @author 马永华
 * @date 2012-10-12 下午3:20:25
 * @version 1.1
 */

public class FileDownloadService {
	
	private ExecutorService executor;

	public FileDownloadService(){
		executor = Executors.newCachedThreadPool();
	}
	
	
	public void downloadAndNotify(String url,String desFileName,Handler handler){
		executor.submit(new SingleDownloadThread(url,desFileName, handler));
	}
	
	//下载一个
	class SingleDownloadThread implements Runnable{
		
		private String url;
		private String desFileName;
		private Handler handler;
		
		public SingleDownloadThread(String url,String desFileName,Handler handler){
			this.desFileName = desFileName;
			this.handler = handler;
			this.url = url;
		}
		
		@Override
		public void run() {
			Downloader downloader = new Downloader();
			downloader.downloadFromUrl(url,desFileName);
			downloader.setOnCompleteListener(new OnCompleteListener() {
				@Override
				public void onComplete(String fileName) {
					//如果有handler
					if(handler!=null){
						Message msg = handler.obtainMessage();
						msg.what = Constants.FILEDOWNLOAD_STATUS_SUCCESS;
						Bundle bundle = new Bundle();
						bundle.putString("name", fileName);
						msg.setData(bundle);
						handler.sendMessage(msg);
					}
				}
			});
			downloader.setOnFileNotExistListener(new OnFileNotExistListener() {
				@Override
				public void onFileNotExist(String fileName) {
					if(handler!=null){
						Message msg = handler.obtainMessage();
						msg.what = Constants.FILEDOWNLOAD_STATUS_FAILURE;
						Bundle bundle = new Bundle();
						bundle.putString("name", fileName);
						msg.setData(bundle);
						handler.sendMessage(msg);
					}
				}
			});
		}
	}
	
}

